#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class TableView(QTableView):
    select_row = 0
    header = []

    def __init__(self, parent=None):
        '''表格初始化'''
        super(QTableView, self).__init__(parent)
        self.model = QStandardItemModel(0, 0)
        self.setModel(self.model)
        # 下面代码让表格100填满窗口
        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 多选
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        # 点击事件
        self.clicked.connect(self.handleItemClicked)

    def setHeader(self, header=[]):
        self.header= header
        self.model.setHorizontalHeaderLabels(self.header)  #

    def handleItemClicked(self, item):
        self.select_row = item.row()

    def clearData(self):
        self.model.clear()
        self.model = QStandardItemModel(0, 0)
        self.model.setHorizontalHeaderLabels(self.header)  #
        self.setModel(self.model)

    def addRow(self, data):
        rows = self.model.rowCount()  # 总行数
        for i in range(0, len(data)):
            self.model.setItem(rows, i, QStandardItem(data[i]))
    
    def deleteRow(self):
        self.model.removeRow(self.select_row)

    def getRows(self):
        rows = self.model.rowCount()  # 总行数
        cols = self.model.columnCount()  # 总行数
        data = []
        for r in range(0, rows):
            row_data = []
            for c in range(0, cols):
                row_data.append(self.model.data(self.model.index(r, c)))
            data.append(row_data)
        return data
